package network.udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

import state.group.ElevatorStruct;
import system.GlobalData;

import messages.BaseMessage;
import messages.GeneralAck;
import messages.MessageFactory;
import messages.MessageType;

public class UDPMessageManager {
    
    public static GeneralAck sendMessage(byte elevatorId, BaseMessage message)
    {
        InetAddress elevatorAddr;
        int elevatorPort;
        
        synchronized (GlobalData.class)
        {
            elevatorAddr = GlobalData.groupState.elevatorIPs.get(elevatorId);
            elevatorPort = GlobalData.groupState.elevatorData.get(elevatorId).udpPort;
        }
        
        
        byte[] data = message.toByteArray();
        
        DatagramPacket outPacket = new DatagramPacket(data, data.length, elevatorAddr, elevatorPort);
        DatagramSocket socket = null;
        
        try
        {
             socket = new DatagramSocket();
        }
        catch (IOException e)
        {
            e.printStackTrace();
            return null;
        }
        
        try
        {
            socket.send(outPacket);
        }
        catch (IOException e)
        {
            e.printStackTrace();
            socket.close();
            return null;
        }
        
        byte[] responseBuf = new byte[ElevatorStruct.MAX_MESSAGE_SIZE];
        DatagramPacket inPacket = new DatagramPacket(responseBuf, responseBuf.length);
        
        try
        {
            socket.receive(inPacket);
        }
        catch (IOException e)
        {
            e.printStackTrace();
            socket.close();
            return null;
        }
        
        BaseMessage response = MessageFactory.parseMessage(responseBuf);
        
        if (response.getMessageType() == MessageType.GeneralAck)
        {
            return (GeneralAck) response;
        }
        
        return null;
    }

    private UDPMessageManager() {}
}
